package com.t235.gc.configs.config;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * JwtToken生成的工具类
 * JWT token的格式：header.payload.signature
 * header的格式（算法、token的类型）：
 * {"alg": "HS512","type": "JWT"}
 * payload的格式（用户名、创建时间、生成时间）：
 * {"sub":"wang","created":1489079981393,"exp":1489684781}
 * signature的生成算法：
 * HMACSHA512(base64UrlEncode(header) + "." +base64UrlEncode(payload),secret)
 */

public class JwtTokenUtil {
    private static final Logger LOGGER = LoggerFactory.getLogger(JwtTokenUtil.class);

    private static final String CLAIM_KEY_USERNAME = "sub";

    private static final String CLAIM_KEY_CREATED = "created";
    public static final String TOKEN_HEADER = "Authorization";
    public static final String TOKEN_PREFIX = "Bearer ";
    //签发者
    private static final String ISS = "long";
    //角色的key
    private static final String ROLE_CLAIMS = "rol";
    //秘钥
    private static final String SECRET="jwtSECRET";
    //过期时间EXPIRATION
    private static final  Long EXPIRATION=3600L;
    //之后的过期时间
    private static final  Long EXPIRATION_REMEMBER=604800L;

    /**
     * 根据负责生成JWT的token
     */
    private String generateToken(Map<String, Object> claims) {
        return Jwts.builder()
                .setClaims(claims)
                .setExpiration(generateExpirationDate())
                .signWith(SignatureAlgorithm.HS512, SECRET)
                .compact();
    }
    public static String createToken (String username, List<String> roles, boolean isRememberMe){
    Long expiration= isRememberMe ? EXPIRATION_REMEMBER: EXPIRATION;
    HashMap<String, Object> map= new HashMap<>();
    map.put(ROLE_CLAIMS, roles);
     return Jwts.builder()
         .signWith(SignatureAlgorithm.HS512,SECRET)
             .setClaims(map)
             .setIssuer(ISS)
             .setSubject(username)
             .setIssuedAt(new Date())
             .setExpiration(new Date(System.currentTimeMillis()+expiration *1000))
             .compact();
    }
    private Date generateExpirationDate() {
        return new Date(System.currentTimeMillis() + EXPIRATION);
    }
    private static Claims getTokenBody(String token){
        return Jwts.parser()
                .setSigningKey(SECRET)
                .parseClaimsJws(token)
                .getBody();
    }
    public static String getUsername(String token){
        return getTokenBody(token).getSubject();
    }
    public static List<String> getUserRole(String token){
        return (List<String>) getTokenBody(token).get(ROLE_CLAIMS);
    }
    public static  boolean isExpiration(String token){
        return getTokenBody(token).getExpiration().before(new Date());
    }
/*   *//* public static List<String> getUserRole(String token){
        return getTokenBody(token).get();
    }

    private static Claims getTokenBody(String token) {
    }*//*

    *//**
     * 从token中获取JWT中的负载
     *//*
    private Claims getClaimsFromToken(String token) {
        Claims claims = null;
        try {
            claims = Jwts.parser()
                    .setSigningKey(SECRET)
                    .parseClaimsJws(token)
                    .getBody();
        } catch (Exception e) {
            LOGGER.info("JWT格式验证失败:{}",token);
        }
        return claims;
    }



    *//**
     * 从token中获取登录用户名
     *//*
    public String getUserNameFromToken(String token) {
        String username;
        try {
            Claims claims = getClaimsFromToken(token);
            username =  claims.getSubject();
        } catch (Exception e) {
            username = null;
        }
        return username;
    }

    *//**
     * 验证token是否还有效
     *
     * @param token       客户端传入的token
     * @param userDetails 从数据库中查询出来的用户信息
     *//*
    public boolean validateToken(String token, UserDetails userDetails) {
        String username = getUserNameFromToken(token);
        return username.equals(userDetails.getUsername()) && !isTokenExpired(token);
    }

    *//**
     * 判断token是否已经失效
     *//*
    private boolean isTokenExpired(String token) {
        Date expiredDate = getExpiredDateFromToken(token);
        return expiredDate.before(new Date());
    }

    *//**
     * 从token中获取过期时间
     *//*
    private Date getExpiredDateFromToken(String token) {
        Claims claims = getClaimsFromToken(token);
        return claims.getExpiration();
    }

    *//**
     * 根据用户信息生成token
     *//*
    public String generateToken(UserDetails userDetails) {
        Map<String, Object> claims = new HashMap<>();
        claims.put(CLAIM_KEY_USERNAME, userDetails.getUsername());
        claims.put(CLAIM_KEY_CREATED, new Date());
        return generateToken(claims);
    }

    *//**
     * 判断token是否可以被刷新
     *//*
    public boolean canRefresh(String token) {
        return !isTokenExpired(token);
    }

    *//**
     * 刷新token
     *//*
    public String refreshToken(String token) {
        Claims claims = getClaimsFromToken(token);
        claims.put(CLAIM_KEY_CREATED, new Date());
        return generateToken(claims);
    }*/
}